//
//  HMSettingViewController.m
//  HowToDo
//
//  Created by 李贺 on 2017/1/4.
//  Copyright © 2017年 KY. All rights reserved.
//

#import "HMSettingViewController.h"
#import "HMFeedBackViewController.h"
#import "HMSettingModel.h"
#import <Masonry.h>
#import "HMNetWorkTool.h"
#import "HMAboutViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "HMNewGuideViewController.h"
#define kNotificationCategoryIdentifile @"kNotificationCategoryIdentifile"
#define kNotificationActionIdentifileStar @"kNotificationActionIdentifileStar"
#define kNotificationActionIdentifileComment @"kNotificationActionIdentifileComment"
#define kLocalNotificationKey @"kLocalNotificationKey"
@interface HMSettingViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) HMSettingModel *model;
@property (nonatomic, strong) UISwitch *sw;
@end

@implementation HMSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"设置";
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    self.view.backgroundColor = [UIColor yellowColor];
    //创建tableView
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:tableView];
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view.mas_top);
    }];
    
    tableView.dataSource = self;
    tableView.delegate = self;
    
    // 清空分割线的内边距
    tableView.separatorInset = UIEdgeInsetsZero;
    
}



#pragma mark -代理-
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 1){
        return 2;
    }
    else if (section ==2){
        return 3;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * cellIdentity = @"cell_ID";
    
    UITableViewCell * tableViewCell = [tableView dequeueReusableCellWithIdentifier:cellIdentity];
    if (!tableViewCell ) {
        tableViewCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentity];
    }
    tableViewCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if(indexPath.section < 2){
        tableViewCell.selectionStyle = UITableViewCellSelectionStyleNone;
        UISwitch * sw = [[UISwitch alloc]init];
        tableViewCell.accessoryView = sw;
        if(indexPath.section == 0){
            sw.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"isPushOn"];
            [sw addTarget:self action:@selector(PushNotifications:) forControlEvents:UIControlEventValueChanged];
        }
        if(indexPath.section == 1 && indexPath.row == 0){
            sw.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"isOn"];
            [sw addTarget:self action:@selector(setHeadphonePlay:) forControlEvents:UIControlEventValueChanged];
        }
        else if(indexPath.section == 1 && indexPath.row == 1){
            sw.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"isWiFiOn"];
#warning 下载方法
            [sw addTarget:self action:@selector(wifiDownload:) forControlEvents:UIControlEventValueChanged];
        }

    }
    if(indexPath.section == 0){
        self.model = [HMSettingModel loadSetMenuData][indexPath.row];
    }
    else if (indexPath.section == 1){
        self.model = [HMSettingModel loadSetMenuData][indexPath.row + 1];
    }
    else if (indexPath.section ==2){
        self.model = [HMSettingModel loadSetMenuData][indexPath.row + 3];
    }
    else if (indexPath.section ==3){
        self.model = [HMSettingModel loadSetMenuData][indexPath.row + 6];
        NSString *DocumentsPath = [DownloadManager sharedManager].floderPath;
        float f = [self folderSizeAtPath:DocumentsPath];
        NSString *str = [NSString stringWithFormat:@"%.f",f];
        tableViewCell.detailTextLabel.text = str;
    }
    else if (indexPath.section ==4){
        self.model = [HMSettingModel loadSetMenuData][indexPath.row + 7];
    }
    else if (indexPath.section ==5){
        UILabel *quitLable = [[UILabel alloc] init];
        quitLable.text = @"退出";
        quitLable.textColor = [UIColor orangeColor];
        [tableViewCell addSubview:quitLable];
        [quitLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
        }];

        quitLable.textAlignment = NSTextAlignmentCenter;
        tableViewCell.accessoryType = UITableViewCellAccessoryNone;
        return tableViewCell;
    }
    tableViewCell.textLabel.text = self.model.name;
    return tableViewCell;
}



///设置cell间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section == 1){
        return 30;
    }
    return 15;
}

// 返回每一组的尾部标题
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if(section == 1){
        UIView * v = [[UIView alloc] init];
        
        v.backgroundColor = [UIColor clearColor];
        
        UILabel * remindLable = [[UILabel alloc] init];
        
        remindLable.text = @"开启后,WiFi环境下将自动下载订阅专栏的新更新音频,以及点赞的音频。";
        remindLable.textColor = [UIColor lightGrayColor];
        remindLable.font = [UIFont systemFontOfSize:12];
        
        remindLable.numberOfLines = 0;
        [remindLable sizeToFit];
        remindLable.alpha = 1;
        remindLable.backgroundColor = [UIColor colorWithRed:247/255.0 green:247/255.0 blue:247/255.0 alpha:1];
        
        [v addSubview:remindLable];
        [remindLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(v.mas_left).offset(8);
            make.right.equalTo(v.mas_right).offset(-8);
        }];
        
        return v;
    }
    else
    {
        return nil;
    }
}


///设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 54;
}

///取消选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 2 && indexPath.row == 0){
        [self makeAlertController];
    }
    else if (indexPath.section == 2 && indexPath.row == 1){

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://www.baidu.com"] options:@{} completionHandler:^(BOOL success) {
        }];
    }
    else if (indexPath.section == 2 && indexPath.row == 2){
        [self feedback];
    }
    else if(indexPath.section == 3){
        //清除缓存
        NSString *DocumentsPath = [DownloadManager sharedManager].floderPath;
        [self clearCache:DocumentsPath];
    }
    else if(indexPath.section == 4){
        HMAboutViewController * aboutVC = [[HMAboutViewController alloc] init];
        
        [self.navigationController pushViewController:aboutVC animated:YES];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
        backItem.title = @"返回";
        self.navigationItem.backBarButtonItem = backItem;
    }
    //退出
    else if (indexPath.section ==5){
        [self qute];
    }
}

///退出登录
- (void)qute{
    
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:DocumentsPath];
    for (NSString *fileName in enumerator) {
        [[NSFileManager defaultManager] removeItemAtPath:[DocumentsPath stringByAppendingPathComponent:fileName] error:nil];
    }
    
    
    
    HMNewGuideViewController  *guideVC = [[HMNewGuideViewController alloc]init];
    self.view.window.rootViewController = guideVC;
}

///推荐给好友
- (void)makeAlertController{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle: nil                                                                             message: nil                                                                       preferredStyle:UIAlertControllerStyleActionSheet];
    //添加Button
    [alertController addAction: [UIAlertAction actionWithTitle: @"分享给微信好友" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //处理分享给微信好友
        [[HMNetWorkTool sharedTool]shareTextToPlatformType:1 andShareMessage:@"欢迎使用获得APP"];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"分享到朋友圈" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        //处理分享到朋友圈
        [[HMNetWorkTool sharedTool]shareTextToPlatformType:2 andShareMessage:@"欢迎使用获得APP"];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    [self presentViewController: alertController animated: YES completion: nil];
}

///意见反馈
- (void)feedback{
    HMFeedBackViewController * backVC = [[HMFeedBackViewController alloc] init];
    [self.navigationController pushViewController:backVC animated:YES];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"设置";
    self.navigationItem.backBarButtonItem = backItem;
}

#pragma mark --设置听筒播放--

- (void)setHeadphonePlay:(UISwitch *)sw{
    if(sw.isOn){
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isOn"];
    }else{
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
         [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isOn"];
    }
}

#pragma mark --wifi时下载--

- (void)wifiDownload:(UISwitch *)sw{
    if(sw.isOn){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isWiFiOn"];
        [[HMNetWorkTool sharedTool] isWiFiSuccessBlock:^(NSInteger state) {
            if(state ==2){
                //下载
            }
            else{
                
                //不下载
            }
            
        }];
    }
    else{
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isWiFiOn"];
    }
}


//单个文件的大小
-(long long)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size;
    }
    return 0;
}

//文件夹的总大小
-(float)folderSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    cachePath=[cachePath stringByAppendingPathComponent:path];
    long long folderSize=0;
    if ([fileManager fileExistsAtPath:cachePath])
    {
        NSArray *childerFiles=[fileManager subpathsAtPath:cachePath];
        for (NSString *fileName in childerFiles)
        {
            NSString *fileAbsolutePath=[cachePath stringByAppendingPathComponent:fileName];
            long long size=[self fileSizeAtPath:fileAbsolutePath];
            folderSize += size;
            NSLog(@"fileAbsolutePath=%@",fileAbsolutePath);
            
        }
        //SDWebImage框架自身计算缓存的实现
        folderSize+=[[SDImageCache sharedImageCache] getSize];
        return folderSize/1024.0/1024.0;
    }
    return 0;
}

//同样也是利用NSFileManager API进行文件操作，SDWebImage框架自己实现了清理缓存操作，我们可以直接调用。
-(void)clearCache:(NSString *)path{
    NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    cachePath=[cachePath stringByAppendingPathComponent:path];
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:cachePath]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:cachePath];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *fileAbsolutePath=[cachePath stringByAppendingPathComponent:fileName];
            NSLog(@"fileAbsolutePath=%@",fileAbsolutePath);
            [fileManager removeItemAtPath:fileAbsolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}

#pragma mark --设置推送通知--

- (void)PushNotifications:(UISwitch *)sw{
    if(sw.isOn){
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
            [self sendiOS10LocalNotification];
        } else {
            [self sendiOS8LocalNotification];
        }
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isPushOn"];
    }else{
        for (UILocalNotification *obj in [UIApplication sharedApplication].scheduledLocalNotifications) {
            if ([obj.userInfo.allKeys containsObject:kLocalNotificationKey]) {
                [[UIApplication sharedApplication] cancelLocalNotification:obj];
            }
        }
        //直接取消全部本地通知
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isPushOn"];
    }
}

- (void)sendiOS10LocalNotification
{
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    
    content.body = @"亲爱的读者,您订阅的'夏目'即音频之后首次推出短视频啦,精彩不容错过!长按或下拉查看>>";
    content.badge = @(1);

    content.categoryIdentifier = kNotificationCategoryIdentifile;
    content.userInfo = @{kLocalNotificationKey: @"iOS10推送"};
    content.sound = [UNNotificationSound defaultSound];
    
    //推送附件
    NSString *path = [[NSBundle mainBundle] pathForResource:@"0" ofType:@"mp4"];
    NSError *error = nil;
    UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"AttachmentIdentifile" URL:[NSURL fileURLWithPath:path] options:nil error:&error];
    content.attachments = @[attachment];
    
    //推送类型
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:60 repeats:YES];

    
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"Test" content:content trigger:trigger];
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        NSLog(@"iOS 10 发送推送， error：%@", error);
    }];
}

- (void)sendiOS8LocalNotification
{
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    //触发通知时间
    localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
    //重复间隔
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    
    //通知内容
    localNotification.alertBody = @"i am a test local notification";
    localNotification.applicationIconBadgeNumber = 1;
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    
    //通知参数
    localNotification.userInfo = @{kLocalNotificationKey: @"iOS8推送"};
    
    localNotification.category = kNotificationCategoryIdentifile;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
@end













